
#include <iostream>
#include "ErrorPrint.hpp"

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include <string.h>

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        EP(Error::MAIN_USE_ERROR);
        DIE(Error::MAIN_USE_ERROR);
    }

    std::string _server_ip = argv[1];
    uint16_t _serverport = std::stoi(argv[2]);

    // 创建套接字
    int _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (_sockfd < 0)
    {
        EP(Error::SOCKFD_FAILED);
        DIE(Error::SOCKFD_FAILED);
    }

    struct sockaddr_in _StructForServer;
    memset(&_StructForServer, 0, sizeof(_StructForServer));
    _StructForServer.sin_addr.s_addr = ::inet_addr(_server_ip.c_str());
    _StructForServer.sin_family = AF_INET;
    _StructForServer.sin_port = ::htons(_serverport);

    while (true)
    {

        // 客户端要发送消息了
        std::cout << "Please Enter# ";
        std::string _client_send_info;
        std::getline(std::cin, _client_send_info);

        int _n1 = ::sendto(
            _sockfd,
            _client_send_info.c_str(), _client_send_info.size(),
            0, (struct sockaddr *)&_StructForServer, sizeof(_StructForServer));
        (void)_n1;

        struct sockaddr_in _serveraddr;
        socklen_t _serverlen = sizeof(_serveraddr);
        char _serinfobuffer[1024];
        int _n2 = ::recvfrom(
            _sockfd,
            _serinfobuffer, sizeof(_serinfobuffer) - 1,
            0, (struct sockaddr *)&_serveraddr, &_serverlen);

        if (_n2 > 0)
        {
            _serinfobuffer[_n2] = 0;
            std::cout << _serinfobuffer << std::endl;
        }
    };

    return 0;
}